//获取应用实例

var app = getApp()
Page({
	data: {
		shopname: '德银春',
		streetnum: '2楼',
		linksname: 'play',
		linksphone: '18124747484',
		/* 运费 */
		deliveryType: 0,
		deliveryType01: '平台配送',
		deliveryType02: '到店自取',
		/* 快递方式 */
		liststutas: true,
		/*控制列表隐藏显示 */
		getgoodsway: [{
			way: '平台配送',
			id: 0
		}, {
			way: '到店自取',
			id: 1
		}], //
		getgoodsid: 0,
		shopaddres: '深圳市龙岗区上水径全伟达工业园旮旯云商201', //商家地址
		shoptelphone: '18129238383',
		peison: true,
		/* 控制配送方式属性 */
		coupon: '暂无优惠卷',
		remark: '',
		array: ['请点击选择支付方式','微信支付', '余额支付'],
		objectMultiArray: [{
				id: '',
				name: '请选择'
			},

			{
				id: 0,
				name: '微信支付'
			},
			{
				id: 1,
				name: '余额支付'
			}
		],
		index: 0,
		uid: 0,
		proverbalence: true,
		/* 账户余额密码弹窗 */
		payway: '',
		select: true,
		buttonTitle: '确认支付',
		accountpassword: '' /* 余额支付密码 */

	},
	// 加载

	/* 页面加载事件 */
	onLoad() {




	},
	onShow(options) {
		//this.address();
		let that = this;
		// 用户地址
		that.loadorderlist(); /* 加载订单数据 */
		that.address();

		//let id = options.id;


	},
	// 下拉刷新

	onPullDownRefresh() {

	},

	// 分享

	onShareAppMessage() {

	},
	/* 选择支付方式 */
	bindPickerChange(e) {
		let that = this;
		console.log('picker发送选择改变，携带值为', e.detail.value)
		console.log();
		if (e.detail.value == 0) {
			that.data.payway = '';
		} else if(e.detail.value == 1){
			that.data.payway = 0;
		}else{
			that.data.payway = 1;
		}
			
		this.setData({
			index: e.detail.value
		})
	},
	/* 确定余额支付*/
	formSubmit(e) {
		let that = this;
		let userInfo = wx.getStorageSync('userInfo');
		let base_url = app.globalData.baseurl;
		let _url ='/user/get?id=' + userInfo.userId;
		let accountpassword = e.detail.value.accountpassword;
		that.data.accountpassword = accountpassword;/* 付款密码 */
		let payAmount=that.data.ordertotalprice ;/* 付款金额 */
		console.log(accountpassword);
		if (accountpassword == '') {
			wx.showModal({
				title: "提示",
				content: "请输入余额支付密码",
				showCancel: true,
				success: function(res) {
					if (res.confirm) {
						/*订单支付函数*/
						return false;
					} else if (res.cancel) {
						console.log('用户点击取消');
						return false;
					}
				}
			});
		} else {
			utils.request(userInfo,_url,'post',data,res=>{
				console.log(res);
				if(res.data.status==200){
					let balance = res.data.data.balance;
					if (balance==0||balance==null) {
						balance = 0;
						balance=balance.toFixed(2);
					}
					if(balance<payAmount){
						wx.hideLoading(); /* 隐藏加载框 */
						wx.showModal({
							title: "提示",
							content: "账户余额不足，请去充值。",
							showCancel: true,
							success: function(res) {
								if (res.confirm) {
									/*订单支付函数*/
									return false;
								} else if (res.cancel) {
									return false;
								}
							}
						});
					}else{
						/* 确认余额支付 */
						that.confirmpay();
					}
				}else{
					wx.showModal({
						title: "提示",
						content: res.msg,
						showCancel: true,
						success: function(res) {
							if (res.confirm) {
								/*订单支付函数*/
								return false;
							} else if (res.cancel) {
								return false;
							}
						}
					});
				}
			})
		}
	},
	/* 选择支付方式弹窗 */
	getgoodsway(e) {
		let that = this;
		let id = e.currentTarget.dataset.id;
		console.log(id);
		if (id == 0) {
			that.data.peison = true;
			that.data.yunfei = 20;
		} else {
			that.data.peison = false;
			that.data.yunfei = 0;
		}
		let yunfei = that.data.yunfei;
		let peison = that.data.peison;
		that.setData({
			getgoodsid: id,
			peison: peison,
			yunfei: yunfei,
			deliveryType: id
		});
		that.loadorderlist();
	},
	canseaccountpay(e) {
		this.setData({
			proverbalence: true
		})
	},

	/* 选择收货地址 */
	select_addres(e) {
		wx.navigateTo({
			'url': '../myaddres/myaddres'
		})
	},
	/* 控制列表显示隐藏 */
	orderdetail(e) {
		let that = this;
		let liststutas = this.data.liststutas;
		console.log(liststutas);
		if (liststutas == true) {
			liststutas = false;
			that.setData({
				liststutas: liststutas
			})
		} else {
			liststutas = true;
			that.setData({
				liststutas: liststutas
			})
		}
	},
	/* 加载缓存中的订单数据 */
	loadorderlist(e) {
		let that = this;
		let base_url = app.globalData.baseurl;
		let shopimg = app.globalData.baseimg;
		let orderlist = wx.getStorageSync('orderlist');
		let order = orderlist.order;
		let orderItems = orderlist.orderItems;

		order.orderAmount = Number(order.orderAmount).toFixed(2);
		that.setData({
			shopimg: shopimg,
			order: order,
			orderItems: orderItems
			//ordertotalprice: ordertotalprice
		})

	},
	totalprice(e) {
		let that = this;
		let order = that.data.order;
		let peison = that.data.peison;
		let ordertotalprice = 0;
		if (peison == true) {
			ordertotalprice = Number(order.orderAmount) + Number(that.data.yunfei);
		} else {
			ordertotalprice = order.orderAmount;
		}
		ordertotalprice = Number(ordertotalprice).toFixed(2);
		that.setData({
			ordertotalprice: ordertotalprice
		})
	},
	address(e) {
		let that = this;
		/* let selectaddresd=true;
		wx.setStorageSync('selectaddresd',selectaddresd); */
		let addresdirect = wx.getStorageSync('addresdirect');
		let selectaddresd = wx.getStorageSync('selectaddresd'); //选择地址后存入缓存
		console.log(selectaddresd);
		if (addresdirect) {
			that.query_address();
		} else {
			let addres = selectaddresd;
			console.log(addres);
			addres.deliveryAddress = addres.deliveryAddress.join('');
			console.log(addres.deliveryAddress);
			that.setData({
				addres: addres,
				addreslist: true
			});
			that.freight();
		}
	},
	/*查询地址*/
	query_address(e) {
		let userInfo = wx.getStorageSync('userInfo');
		let that = this;
		let base_url = app.globalData.baseurl;
		let _url = base_url + '/address/query?openId=' + userInfo.openId;
		wx.request({
			url: _url,
			data: {},
			header: {
				'content-type': 'application/json', // 默认值
				'headerId': userInfo.openId,
				'headerValue': userInfo.headerValue
			},
			success: function(res) {
				console.log(res.data)
				let addres = res.data.data;
				if (res.data.status = 200) {
					if (addres.length == 0) { /* 没有选择地址 */
						that.setData({
							addreslist: false
						})
					} else if (addres.length == 1) { /* 只有一个地址 */
						addres[0].deliveryAddress = addres[0].deliveryAddress.split(',');
						that.setData({
							addres: addres[0],
							addreslist: true
						});
						that.freight(); /* 计算运费 */
					} else {
						let addresdefault;
						for (let i = 0; i < addres.length; i++) { /* 选择默认地址 */
							if (addres[i].frequency) {
								addresdefault = addres[i];
							}
						}
						console.log(addresdefault);
						addresdefault.deliveryAddress = addresdefault.deliveryAddress.split(',');
						that.setData({
							addres: addresdefault,
							addreslist: true
						});
						that.freight();
					}
				}
			}
		})
	},
	freight(e) {
		let that = this;
		let area = that.data.addres;
		let orderAmount = that.data.order.orderAmount;
		console.log(orderAmount, that.data.order);
		let userInfo = wx.getStorageSync('userInfo');
		let base_url = app.globalData.baseurl;
		let _url = base_url + '/address/calculateFreight';
		wx.request({
			url: _url,
			method: 'post',
			data: {
				orderAmount: orderAmount, //订单金额
				area: area.deliveryAddress, //地址
			},
			header: {
				'content-type': 'application/x-www-form-urlencoded', // 默认值
				'headerId': userInfo.openId,
				'headerValue': userInfo.headerValue
			},
			success: function(res) {
				console.log(res);
				if (res.data.status == 200) {
					/* 付款成功后清除购物车中的缓存 */
					let freight = res.data.data;
					freight = Number(freight).toFixed(2);
					that.setData({
						yunfei: freight
					})
					that.totalprice() /* 计算总价 */
				}

			}
		})

	},
	remark(e) {
		let that = this;
		that.data.remark = e.detail.value;
	},
	/**生成商户订单 */
	generateOrder(e) {
		let that = this;
		/* 没有收获地址 */
		if (!that.data.addres) {
			wx.showModal({
				title: "提示",
				content: "请选择收货地址",
				showCancel: true,
				success: function(res) {
					if (res.confirm) {
						/*订单支付函数*/
						console.log('用户点击确定');
						return false;
					} else if (res.cancel) {
						console.log('用户点击取消');
						return false;
					}
				}
			});
		}
		let payway = that.data.payway;
		console.log(payway);
		if (payway === 0 || payway === 1) {
			/* 确认是否支付弹窗 */
			wx.showModal({
				title: "提示",
				content: "是否确认支付",
				showCancel: true,
				success: function(res) {
					if (res.confirm) {
						/*订单微信支付函数*/
						if (that.data.payway == 0) {
							that.confirmpay();
						} else if (that.data.payway == 1) {
							that.setData({
								proverbalence: false
							})
						}

					} else if (res.cancel) {
						console.log('用户点击取消');
						return false;
					}
				}
			});

		} else {
			console.log(payway);
			wx.showModal({
				title: "提示",
				content: "请选择支付方式",
				showCancel: true,
				success: function(res) {
					if (res.confirm) {
						/*订单支付函数*/
						return false;
					} else if (res.cancel) {
						console.log('用户点击取消');
						return false;
					}
				}
			});
			return false;
		}
	},
	confirmpay(e) {
		let that = this;
		//生成商户订单
		let userInfo = wx.getStorageSync('userInfo');
		let base_url = app.globalData.baseurl;
		let _url = base_url + '/wxPay/pay';
		let order = that.data.order;
		let freightCharge = that.data.yunfei;
		let payAmount = that.data.ordertotalprice;
		let addressId = that.data.addres.id;
		let deliveryType = that.data.deliveryType;
		let accountpassword = that.data.accountpassword;
		let payway = that.data.payway;
		wx.showLoading({
			title: '客官不要急~',
			mask: true
		})
		wx.request({
			url: _url,
			method: 'post',
			data: {
				payWay: payway,
				password: accountpassword,
				payAmount: payAmount, //付款金额
				deliveryType: 0, //配送方式  0：平台配送 1：自取
				freightCharge: freightCharge, //订单运费
				addressId: addressId, //收货地址id
				orderNumber: order.orderNumber, //唯一订单号
				orderAmount: order.orderAmount,
				buyerOpenId: userInfo.openId
			},
			header: {
				'content-type': 'application/x-www-form-urlencoded', // 默认值
				'headerId': userInfo.openId,
				'headerValue': userInfo.headerValue
			},
			success: function(res) {
				console.log(res);
				let pay = res.data.data;
				if (res.data.status == 200) {
					/* 余额支付 */
					wx.hideLoading(); /* 隐藏加载框 */
					if (that.data.payway == 1) {
						wx.showToast({
							title: '支付成功',
							icon: 'none'
						})
						wx.redirectTo({
							'url': '../myorder/myorder?type=1'
						})
						return false;
					} else {
						let timeStamp = pay.timeStamp;
						let packages = pay.package;
						let paySign = pay.paySign;
						let nonceStr = pay.nonceStr;
						let param = {
							"timeStamp": timeStamp,
							"package": packages,
							"paySign": paySign,
							"signType": "MD5",
							"nonceStr": nonceStr
						};
						/* 支付 */
						that.pay(param);
					}

				} else {
					wx.showToast({
						title: res.data.msg,
						icon: 'none'
					})
					return false;
				}
			},
		})
	},
	/* 支付  */
	pay(param) {
		wx.hideLoading(); /* 隐藏加载框 */
		wx.requestPayment({
			timeStamp: param.timeStamp,
			nonceStr: param.nonceStr,
			package: param.package,
			signType: param.signType,
			paySign: param.paySign,
			success: function(res) {
				console.log(res);
				if (res.errMsg == "requestPayment:ok") { // 调用支付成功
					wx.redirectTo({
						'url': '../myorder/myorder?type=1'
					})
				} else if (res.errMsg == 'requestPayment:cancel') {
					return false;
				}
			},
			fail: function(res) {
				//fail
			},
			complete: function() {
				//complete
			}
		})
	}






})
